package com.taptech.doufu.ui.fragment.NovelChildFragments;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.taptech.doufu.ui.view.viewflow.view.CircleFlowIndicator;
import com.taptech.doufu.ui.view.viewflow.view.HomeViewFlow;
import com.taptech.doufu.ui.view.viewflow.view.LayersLayout;
import com.taptech.doufu.ui.view.viewflow.view.ViewFlowAdImageAdapter;
import com.taptech.doufu.ui.view.TTHomeViewPager;
import com.taptech.doufu.util.CacheUtil;
import com.taptech.doufu.util.ScreenUtil2;
import com.taptech.doufu.R;
import com.taptech.doufu.ui.adapter.AlbmusAdapter2;
import com.taptech.doufu.bean.AlbumsBean;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.HomeMainServices;
import com.taptech.doufu.ui.fragment.SweepFragment;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.ImageManager;
import com.taptech.doufu.util.StartActivityUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.HomeNovelListView;
import com.taptech.doufu.ui.view.PullToRefreshListView.OnLoadAndRefreshListener;
import com.taptech.doufu.ui.view.PullToRefreshListView.OnScrollToBottomListener;
import com.taptech.doufu.ui.view.RoundImageView;
import com.taptech.doufu.ui.view.WaitDialog;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

public class RankNovelFragment extends SweepFragment implements HttpResponseListener
{

    protected HomeNovelListView mSweepListView;
    protected AlbmusAdapter2 listViewAdapter;
    // http请求中
    protected String last = "";
    protected boolean hasMoreContent = false;
    protected List<AlbumsBean> mainList;
    protected WaitDialog dialog;
    protected ImageView mFragmentLayout;
    private LayersLayout rootlayout;
    private String url="";

//    public RankNovelFragment()
//    {
//
//    }

    public RankNovelFragment(String url)
    {
        this.url=url;
    }

    public RankNovelFragment(TTHomeViewPager mViewPager)
    {
        this.viewPager = mViewPager;
    }

    public RankNovelFragment(){}

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume()
    {
        super.onResume("RankNovelFragment", this.getActivity());
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View fragment1Layout = inflater.inflate(R.layout.sweep_fragment_layout, container, false);
        initView(fragment1Layout);
        loadLatestData();
       /* if (mainList == null)
        {
            loadLatestData();
        } else
        {
            listViewAdapter.notifyDataSetChanged();
            showAdBanner(topList);

        }*/
        return fragment1Layout;
    }

    protected void initView(View parent)
    {
        mSweepListView = (HomeNovelListView) parent.findViewById(R.id.sweep_fragment_listview);
        rootlayout = (LayersLayout) parent.findViewById(R.id.layerslayout);
        mFragmentLayout = (ImageView) parent.findViewById(R.id.fragment_background_id);
        mSweepListView.setRefreshable(true);
        mSweepListView.setLoadmoreable(true);
        listViewAdapter = new AlbmusAdapter2(getActivity());
        mSweepListView.setAdapter(listViewAdapter);
        mSweepListView.setOnLoadAndRefreshListener(new OnLoadAndRefreshListener()
        {

            @Override
            public void onRefresh()
            {
                loadLatestData();
            }

            @Override
            public void loadMore()
            {
                // TODO Auto-generated method stub

            }
        });
        mSweepListView.setOnScrollToBottomListener(new OnScrollToBottomListener()
        {

            @Override
            public void OnScrollToBottom()
            {
                loadMoreData();
            }
        });
        mSweepListView.setAdapter(listViewAdapter);
        // 获取数据并显示专题图
        showAlbums(topAlbumsList);
    }

    @Override
    public void handleResponse(int handleType, final HttpResponseObject response)
    {
        MobclickAgent.onEvent(getActivity(), "sweep-more-latest");
        if (dialog != null)
        {
            mSweepListView.onRefreshComplete();
            mSweepListView.loadMoreComplete();
            dialog.dismiss();
        }
        // 如果未响应提示
        if (response == null)
        {
            UIUtil.toastMessage(getActivity(), Constant.loadingFail);
            return;
        }

        switch (handleType)
        {
            case HomeMainServices.HANDLE_TYPE_LOAD_RANK:
            {
                //  mSweepListView.onRefreshComplete();
                // mSweepListView.loadMoreComplete();
                JSONObject jsonObject = null;
                if (response.getStatus() == Constant.STATUS_SUCCESS)
                {
                    if ((last == null) || (last.equals("")))
                    {
                        jsonObject = (JSONObject) response.getData();
                        try
                        {
                            new Thread(new Runnable()
                            {
                                @Override
                                public void run()
                                {
                                    CacheUtil.saveJsonDataToCache(response.getData().toString(), new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + "NOVELRANKED"));
                                }
                            }).start();
                        } catch (Exception e)
                        {
                            e.printStackTrace();
                        }
                    }
                } else
                {
                    UIUtil.toastMessage(getActivity(), DiaobaoUtil.getErrorTips(response));
                    try
                    {
                        if ((last == null) || (last.equals("")))
                        {
                            jsonObject = CacheUtil.readJsonDataFromCache(new File(Constant.AppDir.FILE_CACHE_DATA_MAIN + "NOVELRANKED"));
                        }
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }

                try
                {
                    if (jsonObject.get("items") instanceof JSONArray)
                    {
                        if (last.equals(""))
                        {
                            mainList = DiaobaoUtil.json2list(AlbumsBean.class, jsonObject.getJSONArray("items"));
                            hasMoreContent = true;
                            // 获取数据并显示专题图
                            getTopDate(jsonObject);
                            listViewAdapter.setDataSource(mainList);
                            mSweepListView.setFull(false);
                            mSweepListView.onRefreshComplete();
                            mSweepListView.loadMoreComplete();
                            mSweepListView.setLoadmoreable(true);
                        } else if (!last.equals(jsonObject.getString("last")))
                        {
                            if (mainList != null)
                            {
                                mainList.addAll(DiaobaoUtil.json2list(AlbumsBean.class, jsonObject.getJSONArray("items")));
                                // 获取数据并显示专题图
                                getAlbumsData(jsonObject);
                                listViewAdapter.setSuperDatas(mainList);
                            }
                            mSweepListView.setFull(false);
                            mSweepListView.loadMoreComplete();
                            mSweepListView.setLoadmoreable(true);
                            hasMoreContent = true;
                        } else
                        {
                            mSweepListView.setFull(true);
                            mSweepListView.loadMoreComplete();
                            mSweepListView.setLoadmoreable(false);
                            // mSweepListView.setFull(true);
                            // mSweepListView.getLoadCompleteImg().setVisibility(View.VISIBLE);
                            // mSweepListView.getFootView().setVisibility(View.VISIBLE);
                            hasMoreContent = false;
                        }
                        if (mainList != null && mainList.size() > 0)
                        {
                            //隐藏无内容图
                            mFragmentLayout.setVisibility(View.GONE);
                        }
                        last = jsonObject.getString("last");
                    }
                } catch (JSONException e)
                {
                    if (response.getUser_msg() != null)
                    {
                        UIUtil.toastMessage(getActivity(), "数据加载错误");
                        e.printStackTrace();
                    }
                }
                break;
            }

            default:
                break;
        }

    }

    private ViewFlowAdImageAdapter viewFlowAdapter;
    private HomeViewFlow viewFlow;
    private CircleFlowIndicator flowIndicator;
    protected List<HomeTopBean> topList;
    private TTHomeViewPager viewPager;

    @SuppressWarnings("unchecked")
    private void getTopDate(JSONObject jsonObject)
    {
        try
        {
            if (jsonObject.has("top"))
            {
                JSONArray topArray = jsonObject.getJSONArray("top");
                topList = DiaobaoUtil.json2list(HomeTopBean.class, topArray);
                //topList = DiaobaoUtil.jsonArray2BeanList(HomeTopBean.class, topArray);
            }

        } catch (JSONException e)
        {
            e.printStackTrace();
        }
        showAdBanner(topList);
    }

    View header;

    private void showAdBanner(List<HomeTopBean> topList)
    {
        if (topList == null || (topList != null && topList.size() == 0))
        {
            return;
        }
        if (header != null)
        {
            if (mSweepListView.getHeadView() != null)
            {
                mSweepListView.removeHeaderView(header);
            }
            mSweepListView.addHeaderView(header);
            listViewAdapter.addHeaderView(true);
            return;
        }
        if (viewFlowAdapter != null)
        {
            viewFlow.stopAutoFlowTimer();
            viewFlowAdapter = new ViewFlowAdImageAdapter(getActivity(), topList);
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            header = inflater.inflate(R.layout.home_head_viewflow, null);
            viewFlow = (HomeViewFlow) header.findViewById(R.id.exchange_ad_viewflow);
            viewFlow.setAdapter(viewFlowAdapter);
            // viewFlow.setImagAdapter(viewFlowAdapter);
            viewFlow.setFlowIndicator(flowIndicator);
            viewFlow.setmSideBuffer(topList.size());// 实际图片张数为size大小
            viewFlow.setTimeSpan(4000);// 图片切换时间间隔
            viewFlow.setSelection(3 * 1000); // 设置初始位置
            flowIndicator.setVisibility(View.VISIBLE);
            viewFlow.setViewPage(viewPager);
            if (topList.size() > 0)
            {
                viewFlow.startAutoFlowTimer(); // 启动自动播放
            }
        } else
        {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            header = inflater.inflate(R.layout.home_head_viewflow, null);
            viewFlow = (HomeViewFlow) header.findViewById(R.id.exchange_ad_viewflow);
            viewFlow.setLayoutParams(new RelativeLayout.LayoutParams(ScreenUtil2.SCREEN_PX_WIDTH, ScreenUtil2.SCREEN_PX_WIDTH / 2));
            flowIndicator = (CircleFlowIndicator) header.findViewById(R.id.exchange_ad_indicator);
            viewFlowAdapter = new ViewFlowAdImageAdapter(getActivity(), topList);
            viewFlow.setAdapter(viewFlowAdapter);
            // viewFlow.setImagAdapter(viewFlowAdapter);
            viewFlow.setFlowIndicator(flowIndicator);
            viewFlow.setmSideBuffer(topList.size());// 实际图片张数为size大小
            viewFlow.setTimeSpan(4000);// 图片切换时间间隔
            viewFlow.setSelection(3 * 1000); // 设置初始位置
            viewFlow.setViewPage(viewPager);
            viewFlow.getParent().requestDisallowInterceptTouchEvent(true);
            flowIndicator.setVisibility(View.VISIBLE);
            if (topList.size() > 0)
            {
                viewFlow.startAutoFlowTimer(); // 启动自动播放
            }

            mSweepListView.addHeaderView(header);
            rootlayout.setView(viewFlow); // 将viewFlow对象传递给自定义图层，用于对事件进行重定向
        }
    }

    protected synchronized void loadLatestData()
    {
        last = "";
        HomeMainServices.getInstance().loadRankNovelDataWithUrl(this,url,"");
    }

    /**
     * 上拉加载更多
     */
    protected synchronized void loadMoreData()
    {
        if (hasMoreContent)
        {
            hasMoreContent = false;
            HomeMainServices.getInstance().loadRankNovelDataWithUrl(this,url,last);
        } else
        {

        }
    }

    /**
     * 顶部UI
     */
    private RoundImageView[] mHeandAlbums;
    /**
     * 获取顶部专题数据
     */
    private List<AlbumsBean> topAlbumsList;

    private void getAlbumsData(JSONObject jsonObject)
    {
        try
        {
            if (jsonObject.has("albums"))
            {
                JSONArray albumsArray = jsonObject.getJSONArray("albums");
                topAlbumsList = DiaobaoUtil.jsonArray2BeanList(AlbumsBean.class, albumsArray);
            }
            showAlbums(topAlbumsList);
        } catch (JSONException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 显示顶部专题图
     *
     * @param topAlbumsList
     */
    private void showAlbums(final List<AlbumsBean> topAlbumsList)
    {
        if (topAlbumsList == null || (topAlbumsList != null && topAlbumsList.size() == 0))
        {
            return;
        }
        if (mSweepListView.getHeaderViewsCount() == 1)
        {
            mHeandAlbums = new RoundImageView[2];
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View header = inflater.inflate(R.layout.home_new_item_albums_1, null);
            header.setBackgroundColor(Color.parseColor("#f7f7f7"));
            mHeandAlbums[0] = (RoundImageView) header.findViewById(R.id.home_new_item_albums_1_log_1);
            mHeandAlbums[1] = (RoundImageView) header.findViewById(R.id.home_new_item_albums_1_log_2);
            mSweepListView.addHeaderView(header);
        }
        for (int i = 0; i < (topAlbumsList.size() > 2 ? 2 : topAlbumsList.size()); i++)
        {
            mHeandAlbums[i].setRectAdius(ScreenUtil2.dip2px(4));
            ImageManager.displayImage(mHeandAlbums[i], topAlbumsList.get(i).getIcon());
            final int p = i;
            mHeandAlbums[i].setOnClickListener(new OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    StartActivityUtil.albumsOnclick(getActivity(), topAlbumsList.get(p));
                }
            });
        }
    }
}